<template>
	<view class="container">
		<!-- 顶部搜索栏（保持你原有的样式） -->
		<view class="search">
			<view class="search-con">
				<view class="search-con-keyword">
					<input class="search-con-keyword-inp" type="text" v-model="searchKeyword"
						placeholder="输入物料编码、物料名称或型号" @input="searchChange" :auto-focus="showFocus" />
					<view class="search-con-keyword-submit" @click="search()">
						<text class="search-keyword-submit-text">搜索</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 取料列表 -->
		<view class="inventory-list">
			<!-- 列表标题（保持你原有的样式） -->
			<view class="list-header">

				<text class="header-item" style="width: 18%">货道</text>
				<text class="header-item" style="width: 18%">库存</text>
				<text class="header-item" style="width: 30%">名称</text>
				<text class="header-item" style="width: 18%">取料数</text>
				<text class="header-item" style="width: 16%">操作</text>
			</view>

			<!-- 列表内容（新增） -->
			<!-- 新增列表内容容器，设置固定高度和滚动 -->
			<scroll-view scroll-y class="list-content">
				<!-- 列表内容（新增） -->
				<view class="list-item" v-for="(item, index) in filteredList" :key="index">
					<text class="item-column location" style="width: 18%">{{ item.identification || '-' }}</text>
					<text class="item-column stock" style="width: 18%">{{ item.now_num || 0 }}</text>
					<text class="item-column name" style="width: 30%">{{ item.material_name || '-' }}</text>
					<text class="item-column stock" style="width: 18%">{{ item.num || 0 }}</text>
					<view class="item-column action" style="width: 16%">
						<button class="action-btn" @click="handleAdjust(index)">取料</button>
					</view>
				</view>
			</scroll-view>

		</view>

		<!-- 底部确认按钮（新增） -->
		<view class="footer">
			<button class="confirm-btn" @click="submit">确认提交</button>
		</view>
	</view>
</template>

<script>
	const API = require("../../utils/apiConfig.js");
	export default {
		data() {
			return {
				searchKeyword: '',
				showFocus: false,
				cabinetSelectValue: {},
				categorySelectValue: '',
				takeData: [],
				list: [],
				pendingResponses: new Map(), // 用于跟踪等待中的响应
				currentOperation: null, // 当前正在处理的操作
				operationQueue: [], // 操作队列
				isProcessing: false, // 是否正在处理队列
				successData: [] // 存储成功取料的记录

			}
		},
		computed: {
			// 过滤后的列表
			filteredList() {
				if (!this.searchKeyword) return this.list;
				const keyword = this.searchKeyword.toLowerCase();
				return this.list.filter(item =>
					(item.material_name && item.material_name.toLowerCase().includes(keyword)) ||
					(item.identification && item.identification.toLowerCase().includes(keyword))
				);
			}
		},
		onShow() {
			this.modelselect()
		},
		onPullDownRefresh() {
			this.getCanPullMaterial('refresh');
			console.log('下拉刷新');
			setTimeout(() => {
				uni.stopPullDownRefresh(); // 停止刷新动画
			}, 1000);
		},
		methods: {

			// 搜索输入变化
			searchChange() {
				this.getCanPullMaterial('refresh');
			},

			modelselect() {
				API.modelselect({

				}).then((res) => {
					console.log("freighttrack     " + JSON.stringify(res));
					this.cabinetSelectRange = res.data;
					this.cabinetSelectValue = res.data[0];
					this.getCanPullMaterial('refresh');
				})
			},
			// 执行搜索
			search() {
				// 这里可以调用API获取数据
				console.log("搜索关键词:", this.searchKeyword);
				this.getCanPullMaterial('refresh');
			},
			getCanPullMaterial(type) {
				this.takeData=[];
				API.takematerial({
					page: this.pageIndex,
					rows: 60,
					st_name: this.cabinetSelectValue.st_name,
					category_name: this.categorySelectValue,
					search: this.searchKeyword
				}).then((res) => {
					console.log("res    " + JSON.stringify(res));
					if (res.code == 0) {
						this.list = res.data.list;
						
					}
				});
				
			},
			// 调整库存
			handleAdjust(index) {
				uni.showModal({
					title: '取料数量',
					content: '',
					editable: true,
					placeholderText: `当前数量: ${this.filteredList[index].now_num}`,
					success: (res) => {
						if (res.confirm && res.content) {
							let newValue = parseInt(res.content);
							if (!isNaN(newValue)) {
								// 更新本地数据
								if (newValue > this.filteredList[index].now_num) {
									newValue = this.filteredList[index].now_num;
									uni.showToast({
										icon: "error",
										title: '超出最大库存'
									})
								}
								if (newValue < 0) {
									newValue = 0;
									uni.showToast({
										icon: "error",
										title: '取料不能小于0'
									})
								}

								// 设置取料数量
								this.$set(this.filteredList[index], 'num', newValue);

								// 处理takeData数组
								const id = this.filteredList[index].id;
								const existingItemIndex = this.takeData.findIndex(item => item.id ===
									id);

								if (newValue > 0) {
									// 如果数量大于0，添加或更新takeData中的数据
									if (existingItemIndex !== -1) {
										// 如果已存在，更新数量
										this.takeData[existingItemIndex].num = newValue;
									} else {
										// 如果不存在，添加新数据
										this.takeData.push({
											id: this.filteredList[index].id,
											x: this.filteredList[index].x,
											y: this.filteredList[index].y,
											registeras: this.filteredList[index].registeras,
											is_direction: this.filteredList[index].is_direction,
											model_code: this.filteredList[index].model_code,
											material_name: this.filteredList[index].material_name,
											identification: this.filteredList[index].identification,
											now_num: this.filteredList[index].now_num,
											num: newValue,
											material_id: this.filteredList[index].material_id
										});
									}
								} else {
									// 如果数量等于0，从takeData中移除
									if (existingItemIndex !== -1) {
										this.takeData.splice(existingItemIndex, 1);
									}
								}
							}
						}
					}
				});
			},

			// 确认提交
			async submit() {
				// 获取所有修改过的数据
				// const changedItems = this.list.filter(item => item._modified);
				console.log("提交的数据:" + JSON.stringify(this.takeData));

				await this.processList();
			},

			// 接收mqtt回码
			mqttMsg(topic, msg) {
				console.log("topic is " + topic);
				console.log("message is " + msg);

				try {
					const message = JSON.parse(msg);

					// 只处理 c:23 的消息
					if (message.c === 23) {
						const [result, channel, count] = message.m.split(/[,&]/);

						// 检查是否是当前等待的响应
						if (this.currentOperation && this.currentOperation.y == channel) {
							console.log("============================");
							if (result === '0') {
								console.log(`货道 ${channel} 出货成功`);
								// 记录成功取料
								
								const successItem = JSON.parse(JSON.stringify(this.currentOperation.item));
								
								this.successData.push(successItem);

								this.currentOperation.resolve(); // 解决当前的 Promise
								this.currentOperation = null; // 清空当前操作
							} else if (result === '2') {
								console.error(`货道 ${channel} 电机超时`);
								this.currentOperation.reject(new Error(`货道 ${channel} 电机超时`));
								this.currentOperation = null;
							}
						}
					}
				} catch (e) {
					console.error('解析MQTT消息失败:', e);
				}
			},

			// 发送 MQTT 消息的方法
			send(num, y,item) {
				if (!getApp().globalData.mqttClient || !getApp().globalData.mqttClient.connected) {
					console.log('MQTT not connected');
					return Promise.reject('MQTT not connected');
				}

				return new Promise((resolve, reject) => {
					let timestamp = new Date().getTime();
					console.log("-------->>>>> 发送指令到货道 " + y);

					const payload = JSON.stringify({
						c: 22,
						f: 'ZHZN002',
						t: '868999061201244',
						m: `1,${y}&${num}`,
						s: `${timestamp}`,
						mi: 2
					});

					// 保存当前操作以便mqttMsg可以处理响应
					this.currentOperation = {
						y,
						resolve,
						reject,
						item
					};

					getApp().globalData.mqttClient.publish('ZHZN/868999061201244', payload, (err) => {
						if (err) {
							console.log('publish error: ' + err.message);
							this.currentOperation = null;
							reject(err);
						} else {
							console.log('message sent: ' + payload);
							// 设置超时（例如10秒）
							setTimeout(() => {
								if (this.currentOperation && this.currentOperation.y == y) {
									console.error(`货道 ${y} 响应超时`);
									this.currentOperation.reject(new Error(`货道 ${y} 响应超时`));
									this.currentOperation = null;
								}
							}, 10000);
						}
					});
				});
			},

			// 遍历数组，并按顺序执行操作
			async processList() {
				if (this.isProcessing) {
					console.log('已有操作正在执行');
					return;
				}
				this.successData = []; // 清空之前的成功记录
				this.isProcessing = true;
				uni.showLoading({
					title: '正在取料',
					mask: true
				});

				try {
					for (let i = 0; i < this.takeData.length; i++) {
						const item = this.takeData[i];
						console.log(`开始操作: ${item.material_name} (货道: ${item.identification})`);

						try {
							await this.send(item.num, (item.y - 1) * 10 + item.x,item);
							console.log(`✅ ${item.material_name} 操作完成！`);
						} catch (error) {
							console.error(`❌ ${item.material_name} 操作失败:`, error.message);
							// 可以选择继续或中断
							// break; // 如果要中断后续操作，取消注释
						}
					}
					if (this.successData.length > 0) {
						console.log("提交成功取料记录:", this.successData);
						try {
							const res = await API.xtake({
								rows: JSON.stringify(this.successData)
							});
							console.log("API调用成功:", res);
							this.getCanPullMaterial('refresh');
						} catch (apiError) {
							console.error("API调用失败:", apiError);
							uni.showToast({
								title: '取料成功但记录保存失败',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: '没有成功取料的记录',
							icon: 'none'
						});
					}
					console.log("所有物料操作完成！");
				} catch (error) {
					console.error("操作过程中出错:", error);
				} finally {
					this.isProcessing = false;
					uni.hideLoading();
				}
			},

			// },
			// 加载数据
			loadData() {
				uni.showLoading({
					title: '加载中...'
				});

				// 模拟数据加载
				setTimeout(() => {
					uni.hideLoading();
				}, 500);
			},

		},
		onLoad() {
			this.loadData();
			uni.$on('messageMqtt', this.mqttMsg);
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	/* 搜索框区域（保持你原有的样式） */
	.search {
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.search-con {
		width: 100%;
		display: flex;
		align-items: center;
	}

	.search-con-keyword {
		display: flex;
		width: 100%;
		background-color: #f2f2f2;
		border-radius: 40rpx;
		overflow: hidden;
	}

	.search-con-keyword-inp {
		flex: 1;
		height: 72rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
	}

	.search-con-keyword-submit {
		width: 120rpx;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		background-color: #07c160;
		color: #fff;
		font-size: 28rpx;
	}

	.search-keyword-submit-text {
		font-weight: 500;
	}

	/* 列表样式（优化后的） */
	.inventory-list {
		flex: 1;
		/* 填充剩余空间 */
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		margin: 15rpx;
		display: flex;
		flex-direction: column;
		/* 添加这个，使子元素可以垂直排列 */
	}

	.list-header {
		display: flex;
		background-color: #333847;
		padding: 12px 0;
	}

	.header-item {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		text-align: center;
		font-size: 14px;
		color: #fff;
		padding: 0 5px;
	}

	/* 新增列表内容容器样式 */
	.list-content {
		flex: 1;
		/* 填充父容器的剩余空间 */
		min-height: 0;
		/* 关键：允许内容溢出 */
		overflow-y: auto;
	}

	.list-item {
		display: flex;
		padding: 12px 0;
		border-bottom: 1px solid #f0f0f0;
		align-items: center;
	}

	.item-column {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		text-align: center;
		font-size: 14px;
		padding: 0 5px;
		word-break: break-word;
	}

	.name {
		color: #333;
	}

	.location {
		color: #666;
	}

	.stock {
		color: #333;
	}

	.action-btn {
		width: 80rpx;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0;
		font-size: 24rpx;
		background-color: #333847;
		color: #fff;
		border-radius: 8rpx;
	}


	/* 底部确认按钮（新增） */
	.footer {
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.05);
	}

	.confirm-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #07c160;
		color: #fff;
		font-size: 32rpx;
		border-radius: 40rpx;
	}
</style>